/**
 *====================================================
 * 文件名称: FinanceManagementActionApImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年10月19日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.bulkstock.entity.lexicon.MeasurementEnum;
import com.yuexunit.finance.common.util.CollectionUtils;
import com.yuexunit.finance.common.util.LongUtils;
import com.yuexunit.finance.context.FinanceBaseAction;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.project.action.v1.dto.BulkstockCastor;
import com.yuexunit.finance.project.action.v1.dto.BulkstockManagementCastor;
import com.yuexunit.finance.project.action.v1.model.output.BadassetsHandleDetail;
import com.yuexunit.finance.project.action.v1.model.output.BadassetsHandleLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.ReturnFinanceDetail;
import com.yuexunit.finance.project.action.v1.model.output.ReturnFinanceLineInfo;
import com.yuexunit.finance.project.entity.BadassetsHandleEntity;
import com.yuexunit.finance.project.entity.BadassetsInventoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceReturnBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceReturnEntity;
import com.yuexunit.finance.project.service.BadassetsInventoryService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;

/**
 * @ClassName: FinanceManagementActionApImpl
 * @Description: 保险/处置
 * @author chenxy
 * @date 2015年10月19日 上午8:02:31
 */
@Implements(FinanceBulkstockManagementActionApi.class)
public class FinanceBulkstockManagementActionApImpl extends FinanceBaseAction implements FinanceBulkstockManagementActionApi {
	private BadassetsInventoryService badassetsInventoryService = ComponentFactory.loadClass(BadassetsInventoryService.class);

	@Transactional
	@Override
	public String createReturnFinanceBulkstock(Long financeId, BigDecimal deductionAmount, String remark, Long[] bulkstockIds, BigDecimal[] quantitys, String[] units) {
		FinanceReturnEntity returnEntity = BulkstockManagementCastor.fromFinanceReturn(financeId, deductionAmount, remark);
		Long returnId = financeReturnService.createFinanceReturnEntity(returnEntity);

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setFinanceAmount(financeEntity.getFinanceAmount().subtract(returnEntity.getDeductionAmount()));
		financeApplicationService.renovateFinanceApplication(financeEntity);

		List<FinanceReturnBulkstockEntity> returnBulkstockList = BulkstockManagementCastor.fromFinanceReturnBulkstock(returnId, bulkstockIds, quantitys, units);
		for (FinanceReturnBulkstockEntity entity : returnBulkstockList) {
			financeReturnBulkstockService.createReturnFinanceBulkstock(entity);

			FinanceBulkstockEntity bulkstockEntity = financeBulkstockService.inquireFinanceBulkstock(entity.getBulkstockId());
			bulkstockEntity.setWeight(bulkstockEntity.getWeight().multiply(bulkstockEntity.getQuantity().subtract(entity.getQuantity()).divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP)));
			bulkstockEntity.setVolume(bulkstockEntity.getVolume().multiply(bulkstockEntity.getQuantity().subtract(entity.getQuantity()).divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP)));
			if (MeasurementEnum.VOLUME == bulkstockEntity.getMeasurement()) { // 体积计价
				bulkstockEntity.setValuationQuantity(bulkstockEntity.getVolume());
			} else {
				bulkstockEntity.setValuationQuantity(bulkstockEntity.getWeight());
			}
			bulkstockEntity.setQuantity(bulkstockEntity.getQuantity().subtract(entity.getQuantity()));
			financeBulkstockService.updateFinanceBulkstockEntity(bulkstockEntity);
		}
		return returnId.toString();
	}

	@Transactional
	@Override
	public void updateReturnFinanceBulkstock(Long returnId, BigDecimal deductionAmount, String remark, Long[] returnBulkstockIds, Long[] bulkstockIds, BigDecimal[] quantitys, String[] units) {
		FinanceReturnEntity returnPersist = financeReturnService.inquireReturnFinance(returnId);
		FinanceReturnEntity returnEntity = BulkstockManagementCastor.fromFinanceReturn(returnPersist.getFinanceId(), deductionAmount, remark);
		financeReturnService.updateFinanceReturnEntity(returnEntity);

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(returnPersist.getFinanceId());
		financeEntity.setFinanceAmount(financeEntity.getFinanceAmount().subtract(returnEntity.getDeductionAmount()).add(returnPersist.getDeductionAmount()));
		financeApplicationService.renovateFinanceApplication(financeEntity);

		List<FinanceReturnBulkstockEntity> returnBulkstockPersistList = financeReturnBulkstockService.inquireReturnFinanceBulkstockList(returnId);
		List<FinanceReturnBulkstockEntity> returnBulkstockList = BulkstockManagementCastor.fromFinanceReturnBulkstock(returnId, bulkstockIds, quantitys, units);
		Set<Long> returnBulkstockIdSet = CollectionUtils.convertSet(returnBulkstockIds);
		for (int i = 0; i < returnBulkstockList.size(); i++) {
			FinanceReturnBulkstockEntity entity = returnBulkstockList.get(i);
			entity.setReturnBulkstockId(returnBulkstockIds[i]);
			if (!LongUtils.isPrimaryKey(entity.getReturnBulkstockId())) {
				financeReturnBulkstockService.createReturnFinanceBulkstock(entity);

				FinanceBulkstockEntity bulkstockEntity = financeBulkstockService.inquireFinanceBulkstock(entity.getBulkstockId());
				BigDecimal currentQuantity = bulkstockEntity.getQuantity().subtract(entity.getQuantity());
				bulkstockEntity.setWeight(bulkstockEntity.getWeight().multiply(currentQuantity.divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP)));
				bulkstockEntity.setVolume(bulkstockEntity.getVolume().multiply(currentQuantity.divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP)));
				if (MeasurementEnum.VOLUME == bulkstockEntity.getMeasurement()) { // 体积计价
					bulkstockEntity.setValuationQuantity(bulkstockEntity.getVolume());
				} else {
					bulkstockEntity.setValuationQuantity(bulkstockEntity.getWeight());
				}
				bulkstockEntity.setQuantity(currentQuantity);
				financeBulkstockService.updateFinanceBulkstockEntity(bulkstockEntity);
			} else {
				FinanceReturnBulkstockEntity returnBulkstockPersist = financeReturnBulkstockService.inquireReturnFinanceBulkstock(entity.getReturnBulkstockId());
				financeReturnBulkstockService.updateReturnFinanceBulkstock(entity);

				FinanceBulkstockEntity bulkstockEntity = financeBulkstockService.inquireFinanceBulkstock(entity.getBulkstockId());
				BigDecimal currentQuantity = bulkstockEntity.getQuantity().subtract(entity.getQuantity()).add(returnBulkstockPersist.getQuantity());
				bulkstockEntity.setWeight(bulkstockEntity.getWeight().multiply(currentQuantity.divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP)));
				bulkstockEntity.setVolume(bulkstockEntity.getVolume().multiply(currentQuantity.divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP)));
				if (MeasurementEnum.VOLUME == bulkstockEntity.getMeasurement()) { // 体积计价
					bulkstockEntity.setValuationQuantity(bulkstockEntity.getVolume());
				} else {
					bulkstockEntity.setValuationQuantity(bulkstockEntity.getWeight());
				}
				bulkstockEntity.setQuantity(currentQuantity);
				financeBulkstockService.updateFinanceBulkstockEntity(bulkstockEntity);
			}
		}
		for (FinanceReturnBulkstockEntity entity : returnBulkstockPersistList) {
			if (!returnBulkstockIdSet.contains(entity.getReturnBulkstockId())) {
				FinanceBulkstockEntity bulkstockEntity = financeBulkstockService.inquireFinanceBulkstock(entity.getBulkstockId());
				BigDecimal currentQuantity = bulkstockEntity.getQuantity().add(entity.getQuantity());
				bulkstockEntity.setWeight(bulkstockEntity.getWeight().multiply(currentQuantity).divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP));
				bulkstockEntity.setVolume(bulkstockEntity.getVolume().multiply(currentQuantity).divide(bulkstockEntity.getQuantity(), 10, BigDecimal.ROUND_HALF_UP));
				if (MeasurementEnum.VOLUME == bulkstockEntity.getMeasurement()) { // 体积计价
					bulkstockEntity.setValuationQuantity(bulkstockEntity.getVolume());
				} else {
					bulkstockEntity.setValuationQuantity(bulkstockEntity.getWeight());
				}
				bulkstockEntity.setQuantity(currentQuantity);
				financeBulkstockService.updateFinanceBulkstockEntity(bulkstockEntity);
				financeReturnBulkstockService.deleteReturnFinanceBulkstock(entity.getReturnBulkstockId());
			}
		}
	}

	@Override
	public ReturnFinanceDetail inquireReturnFinanceDetail(Long returnId) {
		FinanceReturnEntity returnEntity = financeReturnService.inquireReturnFinance(returnId);
		return BulkstockManagementCastor.toReturnFinanceDetail(returnEntity);
	}

	@Override
	public PageList<ReturnFinanceLineInfo> inquireReturnFinancePageList(Long financeId, String financeNumber, PageCriteria page) {
		PageList<FinanceReturnEntity> pageList = financeReturnService.inquireReturnFinancePageList(financeId, financeNumber, page);
		PageList<ReturnFinanceLineInfo> resultList = new PageList<ReturnFinanceLineInfo>(page, pageList.getTotalRecordCount());
		for (FinanceReturnEntity entity : pageList) {
			resultList.add(BulkstockManagementCastor.toReturnFinanceLineInfo(entity));
		}
		return resultList;
	}

	// ====================================================================================================================================================//
	@Transactional
	@Override
	public String createBadassetsHandle(Long financeId, Integer handleReson, String transactorMethod, BigDecimal transactorAmount, String transactorRemark, Long[] inventoryIds) {
		if (inventoryIds == null || inventoryIds.length == 0) {
			throw new BusinessException("处置货物不允许为空");
		}
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		BadassetsHandleEntity entity = new BadassetsHandleEntity();
		entity.setHandleReson(handleReson);
		entity.setFinanceId(financeId);
		entity.setFinanceNumber(financeEntity.getFinanceNumber());
		entity.setEnterpriseId(financeEntity.getEnterpriseId());
		entity.setEnterpriseName(financeEntity.getEnterpriseName());
		entity.setTransactor(FinanceSessionContext.getAccountFullName());
		entity.setTransactorId(FinanceSessionContext.getAccountId());
		entity.setTransactorMethod(transactorMethod);
		entity.setTransactorAmount(transactorAmount);
		entity.setTransactorRemark(transactorRemark);
		entity.setTransactorDateTime(DateUtil.now());
		Long badassetsHandleId = badassetsHandleService.createBadassetsHandle(entity);

		for (Long inventoryId : inventoryIds) {
			BadassetsInventoryEntity inventory = new BadassetsInventoryEntity();
			inventory.setBadassetsHandleId(badassetsHandleId);
			inventory.setInventoryId(inventoryId);
			badassetsInventoryService.createBadassetsInventory(inventory);
		}
		return badassetsHandleId.toString();
	}

	@Override
	public BadassetsHandleDetail inquireBadassetsHandleDetail(Long badassetsHandleId) {
		BadassetsHandleEntity entity = badassetsHandleService.inquireBadassetsHandle(badassetsHandleId);
		return BulkstockManagementCastor.toBadassetsHandleDetail(entity);
	}

	@Override
	public PageList<BadassetsHandleLineInfo> inquireBadassetsHandlePageList(Long[] badassetsHandleIds, Long financeId, String financeNumber, Long enterpriseId, String enterpriseName, PageCriteria page) {
		if (FinanceSessionContext.isEnterprise()) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		PageList<BadassetsHandleEntity> pageList = badassetsHandleService.inquireBadassetsHandlePageList(badassetsHandleIds, financeId, financeNumber, enterpriseId, enterpriseName, page);
		PageList<BadassetsHandleLineInfo> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (BadassetsHandleEntity entity : pageList) {
			BadassetsInventoryEntity badEntity = badassetsInventoryService.inquireHandleBadassetsInventoryList(entity.getBadassetsHandleId()).get(0);
			ContainerInventoryEntity containerInventory = containerInventoryService.inquireContainerInventory(badEntity.getInventoryId());
			ContainerInventory result = BulkstockCastor.toContainerInventory(containerInventory, Boolean.FALSE);
			BadassetsHandleLineInfo line = BulkstockManagementCastor.toBadassetsHandleLineInfo(entity);
			line.setContainerInventory(result);
			resultList.add(line);
		}
		return resultList;
	}
}
